<template>
  <div class="layout">
    <div class="login_top">
      <div class="login_top_img">
        <img src="../../../assets/login/login_log.png" alt="" />
      </div>
      <p class="login_top_border"></p>
      <p class="login_top_text">用客易达连接客户</p>
    </div>

    <div class="container">
      <div class="container_top">
        <div class="container_header">
          <span class="container_header_title">全渠道自动化 营销运营平台</span>
          <span class="container_header_text">构建私域流量，打破营销困局</span>
        </div>
      </div>

      <el-form ref="ruleFormRef" :model="numberValidateForm" :rules="rules" label-position="left" label-width="auto" size="large">
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="numberValidateForm.name" placeholder="请填写公司全称" minlength="2" maxlength="50"></el-input>
        </el-form-item>
        <el-form-item label="账号姓名" prop="account">
          <el-input v-model="numberValidateForm.account" placeholder="请填写账号姓名" minlength="2" maxlength="30"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input v-model="numberValidateForm.phone" placeholder="请填写手机号码" maxlength="11" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="imgCode_input" label="图片验证码" prop="imgCode">
          <el-input type="text" v-model="numberValidateForm.imgCode" placeholder="请填写图片验证码" maxlength="4">
            <template #suffix>
              <div class="imgCode" @click="randomCode">
                <img :src="getImgCode" alt="" />
              </div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="短信验证码" prop="verificationCode">
          <el-input type="text" v-model="numberValidateForm.verificationCode" placeholder="请填写短信验证码" maxlength="6">
            <template #suffix>
              <div v-show="sendAuthCode" class="getCode" @click="getPhoneCode">获取验证码</div>
              <div v-show="!sendAuthCode" class="getCode countDown">{{ autoTime }}秒后重新获取</div>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="设置密码" prop="password">
          <el-input autocomplete="off" type="password" v-model="numberValidateForm.password" placeholder="请填写必须包含数字和字母的6-20位密码" minlength="6" maxlength="20"> </el-input>
        </el-form-item>
        <el-form-item label="确认密码" prop="secondaryPassword">
          <el-input type="password" v-model="numberValidateForm.secondaryPassword" placeholder="请填再次输入密码" minlength="6" maxlength="20"> </el-input>
        </el-form-item>

        <div class="check">
          <el-checkbox v-model="checked1"></el-checkbox>
          <p>注册前请仔细阅读 <span class="checkText" @click="handleAgreement('userAgreement')">《用户协议》</span> 和 <span class="checkText" @click="handleAgreement('privacyAgreement')">《隐私声明》</span></p>
        </div>

        <div class="btn">
          <el-button type="primary" @click="submitForm(ruleFormRef)">注册</el-button>
        </div>

        <div class="goLogin">已有账号？ <span @click="gologin">去登录</span></div>
      </el-form>
    </div>

    <div class="copyright">
      <p>Copyright&copy;2021- 2022 keyid.com. 版权所有</p>
      <p>增值电信业务经营许可证： 沪B2-20211704 | 沪ICP备2021020699号-2</p>
    </div>

    <el-dialog v-model="successfullyDialog" width="20%" center class="successfullyDialog" destroy-on-close="true" :before-close="stopClosing">
      <span>注册成功！</span>
      <template #title>
        <el-icon class="check_icon"><Check /></el-icon>
      </template>
      <template #footer>
        <el-button type="primary" @click="gologin">去登录</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { computed, onMounted, reactive, ref } from 'vue'
  import { noteCode, registration } from '@/api/login'
  import { ElMessageBox, ElMessage, ElForm } from 'element-plus'
  import { corpName, validateAcount, validatorPassword, validatePhone, validateCode, validatorNote } from '@/utils/validate'
  import { useStore } from '@/store'
  import router from '@/router'
  import { getImageCode } from '@/api/common'
  const autoTime = ref(-1)
  const checked1 = ref(false)
  let sendAuthCode = ref(true)
  const ruleFormRef = ref<InstanceType<typeof ElForm>>()
  const successfullyDialog = ref(false)
  const getImgCode = ref('')
  const numberValidateForm = reactive({
    name: '',
    account: '',
    phone: '',
    password: '',
    secondaryPassword: '',
    imgCode: '',
    verificationCode: ''
  })
  // 公司名称验证
  let companyName = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('请填写公司全称'))
    else if (corpName(value)) {
      callback(new Error('请输入2-50位长度的企业名称'))
    } else {
      callback()
    }
  }
  //账号姓名验证
  let accountName = (rule: any, value: nay, callback: any) => {
    if (value == '') callback(new Error('请填写账号姓名'))
    else if (validateAcount(value)) {
      callback(new Error('请输入2-30位的账号姓名'))
    } else {
      callback()
    }
  }
  // 手机验证
  let phone = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('手机号不能为空'))
    else if (validatePhone(value)) {
      callback(new Error('手机格式有误!'))
    } else {
      callback()
    }
  }
  // 图片验证
  let auth = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('验证码不能为空!'))
    else if (validateCode(value)) {
      callback(new Error('验证码格式错误!'))
    } else {
      callback()
    }
  }
  // 短信验证
  let note = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('验证码不能为空!'))
    else if (validatorNote(value)) {
      callback(new Error('验证码格式错误!'))
    } else {
      callback()
    }
  }
  // 密码验证
  let password = (rule: any, value: any, callback: any) => {
    if (value == '') {
      callback(new Error('密码不能为空!'))
    } else if (validatorPassword(value)) {
      callback(new Error('密码为6~20位字母+数字组合!'))
    } else callback()
  }
  // 重复密码
  let confirmPassword = (rule: any, value: any, callback: any) => {
    if (value == '') callback(new Error('密码不能为空!'))
    else if (value !== numberValidateForm.password) {
      callback(new Error('输入密码不一致，请重新输入!'))
    } else callback()
  }
  // 规则
  const rules = reactive({
    name: [{ required: true, validator: companyName, trigger: 'change' }],
    phone: [{ required: true, validator: phone, trigger: 'change' }],
    imgCode: [{ required: true, validator: auth, trigger: 'change' }],
    verificationCode: [{ required: true, validator: note, trigger: 'change' }],
    password: [{ required: true, validator: password, trigger: 'change' }],
    secondaryPassword: [{ required: true, validator: confirmPassword, trigger: 'change' }],
    account: [{ required: true, validator: accountName, trigger: 'change' }]
  })
  // 去登录页面
  const gologin = () => {
    router.push({ path: '/login' })
  }
  // 阻止关闭注册成功弹框
  const stopClosing = () => {
    successfullyDialog.value = true
  }
  // 跳转至平台协议
  const handleAgreement = (show: any) => {
    window.open(`/agreement?show=${show}`)
  }
  // 获取图片验证码
  const randomCode = async () => {
    const res: any = await getImageCode({ captcha_type: 'sms_register' })
    getImgCode.value = `data:image/png;base64,${res.base64_image}`
  }

  // 计算短信验证码倒计时
  let smsLockTimeStorage: any = computed({
    get: () => {
      let val = localStorage.getItem('__scrm_register_lock_time__') ?? 0
      return val
    },
    set: (value: any) => {
      localStorage.setItem('__scrm_register_lock_time__', value)
    }
  })

  // 验证码倒计时函数
  const smsLockTick = (num: number) => {
    sendAuthCode.value = false
    autoTime.value = num
    let autoTimeTimer = setInterval(() => {
      autoTime.value--
      smsLockTimeStorage.value = autoTime.value
      if (autoTime.value <= 0) {
        sendAuthCode.value = true
        autoTime.value = 0
        smsLockTimeStorage.value = 0
        clearInterval(autoTimeTimer)
      }
    }, 1000)
  }
  // 从localstorage中初始化验证码计时器
  if (smsLockTimeStorage.value > 0) {
    autoTime.value = smsLockTimeStorage.value
    smsLockTick(autoTime.value)
  } else {
    autoTime.value = 0
  }
  // 获取手机验证码
  const getPhoneCode: () => void = () => {
    if (numberValidateForm.phone != '' && numberValidateForm.imgCode != '') {
      const { phone, imgCode, verificationCode } = numberValidateForm
      let params = {
        mobile: phone + '',
        image_verify_code: imgCode,
        sms_type: 'sms_register'
      }
      noteCode(params)
        .then((data: any) => {
          smsLockTick(60)
        })
        .catch((err: any) => {
          if (err.code == 10001) {
            ElMessage.error(err.msg)
            randomCode()
          }
        })
    } else {
      ElMessage.error('请填写手机号或图片验证码')
    }
  }

  // 提交注册表单
  const submitForm = (formEl: any) => {
    console.log(formEl)

    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        const { name, account, phone, password, secondaryPassword, verificationCode } = numberValidateForm
        const params = {
          corp_name: name,
          name: account,
          mobile: phone,
          password,
          password_confirmation: secondaryPassword,
          sms_code: verificationCode
        }
        if (checked1.value === false) {
          ElMessage.error('注册前请仔细阅读 《用户协议》 和 《隐私声明》')
          return
        }
        registration(params).then((data: any) => {
          successfullyDialog.value = true
        })
      } else {
        return false
      }
    })
  }
  onMounted(() => {
    randomCode()
  })
</script>

<style lang="scss" scoped>
  .layout {
    width: 100%;
    height: 1080px;
    background: url('../../../assets/login/register_bg.png');
    background-size: 100%;
    .login_top {
      height: 60px;
      display: flex;
      align-items: center;
      background: #ffff;
      &_img {
        width: 95px;
        height: 23px;
        margin-left: 40px;
        img {
          width: 100%;
          height: 100%;
        }
      }
      &_border {
        height: 20px;
        margin: 0 14px;
        border-left: 1px solid #d0d0d0;
      }
      &_text {
        font-size: 14px;
        line-height: 14px;
        color: #33302d;
      }
    }
    .container {
      width: 950px;
      height: 830px;
      margin: 40px auto 0;
      background: #ffff;
      &_top {
        .container_header {
          width: 100%;
          height: 137px;
          text-align: center;
          background: url('../../../assets/login/register1_bg.png') no-repeat;
          background-size: cover;
          color: #ffffff;
          &_title {
            font-size: 28px;
            line-height: 28px;
            display: block;
            padding: 40px 0 12px;
          }
          &_text {
            display: block;
            font-size: 14px;
            line-height: 14px;
          }
        }
      }
      .imgCode {
        width: 100px;
        height: 30px;
        margin-top: 4px;
        line-height: 30px;
        background: #f6f6f6;
        text-align: center;
        cursor: pointer;
        img {
          width: 100%;
          height: 100%;
        }
      }
      .getCode {
        color: #0081ff;
        height: 16px;
        font-size: 16px;
        line-height: 16px;
        cursor: pointer;
      }
      .countDown {
        color: #969696;
      }
      .check {
        height: 14px;
        display: flex;
        align-items: center;
        p {
          font-size: 14px;
          color: #969696;
          margin: -2px 0 0 8px;
          span {
            color: #0081ff;
            cursor: pointer;
          }
        }
      }
      .goLogin {
        margin-top: 16px;
        text-align: center;
        color: #696969;
        font-size: 14px;
        span {
          color: #0081ff;
          cursor: pointer;
        }
      }
      :deep(.el-form) {
        width: 430px;
        color: #33302d;
        margin: 68px auto 0;

        .el-form-item {
          border-bottom: 1px solid #d9d9d9;
        }
      }

      :deep(.el-input) {
        .el-input__wrapper {
          padding: 0;
          box-shadow: none;
          box-sizing: border-box;
        }
      }

      .btn {
        margin-top: 30px;

        .el-button {
          width: 100%;
        }
      }
    }
    .copyright {
      text-align: center;
      color: #969696;
      font-size: 14px;
      margin-top: 54px;
      p {
        margin: 0;
        line-height: 14px;
        padding: 3px 0;
      }
    }
    :deep .check_icon {
      display: inline-block;
      width: 35px;
      height: 35px;
      margin-top: 20px;
      line-height: 45px;
      border-radius: 50%;
      font-size: 25px;
      color: #fff;
      background-color: #07c160;
    }
    :deep .el-dialog__body {
      display: flex;
      justify-content: center;
      font-size: 20px;
    }
    :deep .el-dialog__headerbtn .el-dialog__close {
      display: none;
    }
  }
</style>
